package com.yonglian.management.web.rest;

import com.yonglian.management.domain.ActivityStandard;
import com.yonglian.management.repository.ActivityStandardRepository;
import com.yonglian.management.service.ActivityStandardService;
import com.yonglian.management.web.rest.errors.BadRequestAlertException;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.PaginationUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link com.yonglian.management.domain.ActivityStandard}.
 */
@RestController
@RequestMapping("/api/activity-standards")
public class ActivityStandardResource {

    private final Logger log = LoggerFactory.getLogger(ActivityStandardResource.class);

    private static final String ENTITY_NAME = "activityStandard";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final ActivityStandardService activityStandardService;

    private final ActivityStandardRepository activityStandardRepository;

    public ActivityStandardResource(
        ActivityStandardService activityStandardService,
        ActivityStandardRepository activityStandardRepository
    ) {
        this.activityStandardService = activityStandardService;
        this.activityStandardRepository = activityStandardRepository;
    }

    /**
     * {@code POST  /activity-standards} : Create a new activityStandard.
     *
     * @param activityStandard the activityStandard to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new activityStandard, or with status {@code 400 (Bad Request)} if the activityStandard has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("")
    public ResponseEntity<ActivityStandard> createActivityStandard(@Valid @RequestBody ActivityStandard activityStandard)
        throws URISyntaxException {
        log.debug("REST request to save ActivityStandard : {}", activityStandard);
        if (activityStandard.getId() != null) {
            throw new BadRequestAlertException("A new activityStandard cannot already have an ID", ENTITY_NAME, "idexists");
        }
        activityStandard = activityStandardService.save(activityStandard);
        return ResponseEntity.created(new URI("/api/activity-standards/" + activityStandard.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, activityStandard.getId().toString()))
            .body(activityStandard);
    }

    /**
     * {@code PUT  /activity-standards/:id} : Updates an existing activityStandard.
     *
     * @param id the id of the activityStandard to save.
     * @param activityStandard the activityStandard to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated activityStandard,
     * or with status {@code 400 (Bad Request)} if the activityStandard is not valid,
     * or with status {@code 500 (Internal Server Error)} if the activityStandard couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/{id}")
    public ResponseEntity<ActivityStandard> updateActivityStandard(
        @PathVariable(value = "id", required = false) final Long id,
        @Valid @RequestBody ActivityStandard activityStandard
    ) throws URISyntaxException {
        log.debug("REST request to update ActivityStandard : {}, {}", id, activityStandard);
        if (activityStandard.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, activityStandard.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!activityStandardRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        activityStandard = activityStandardService.update(activityStandard);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, activityStandard.getId().toString()))
            .body(activityStandard);
    }

    /**
     * {@code PATCH  /activity-standards/:id} : Partial updates given fields of an existing activityStandard, field will ignore if it is null
     *
     * @param id the id of the activityStandard to save.
     * @param activityStandard the activityStandard to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated activityStandard,
     * or with status {@code 400 (Bad Request)} if the activityStandard is not valid,
     * or with status {@code 404 (Not Found)} if the activityStandard is not found,
     * or with status {@code 500 (Internal Server Error)} if the activityStandard couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
    public ResponseEntity<ActivityStandard> partialUpdateActivityStandard(
        @PathVariable(value = "id", required = false) final Long id,
        @NotNull @RequestBody ActivityStandard activityStandard
    ) throws URISyntaxException {
        log.debug("REST request to partial update ActivityStandard partially : {}, {}", id, activityStandard);
        if (activityStandard.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, activityStandard.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!activityStandardRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<ActivityStandard> result = activityStandardService.partialUpdate(activityStandard);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, activityStandard.getId().toString())
        );
    }

    /**
     * {@code GET  /activity-standards} : get all the activityStandards.
     *
     * @param pageable the pagination information.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of activityStandards in body.
     */
    @GetMapping("")
    public ResponseEntity<List<ActivityStandard>> getAllActivityStandards(
        @org.springdoc.core.annotations.ParameterObject Pageable pageable
    ) {
        log.debug("REST request to get a page of ActivityStandards");
        Page<ActivityStandard> page = activityStandardService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * {@code GET  /activity-standards/:id} : get the "id" activityStandard.
     *
     * @param id the id of the activityStandard to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the activityStandard, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<ActivityStandard> getActivityStandard(@PathVariable("id") Long id) {
        log.debug("REST request to get ActivityStandard : {}", id);
        Optional<ActivityStandard> activityStandard = activityStandardService.findOne(id);
        return ResponseUtil.wrapOrNotFound(activityStandard);
    }

    /**
     * {@code DELETE  /activity-standards/:id} : delete the "id" activityStandard.
     *
     * @param id the id of the activityStandard to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteActivityStandard(@PathVariable("id") Long id) {
        log.debug("REST request to delete ActivityStandard : {}", id);
        activityStandardService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
